 #!/usr/bin/env bash

#Centos7设置网卡IP 和 yum库

#HOST_IP=192.168.72.120
HOST_IP=${1:-192.168.72.120}
GATEWAY=192.168.72.2

setHostIPV4() {
    grep IPADDR= /etc/sysconfig/network-scripts/ifcfg-ens33
    if [ $? == 0 ]
    then
        sed -i "s/^IPADDR=.*/IPADDR=${HOST_IP}/g" /etc/sysconfig/network-scripts/ifcfg-ens33
        sed -i "s/^GATEWAY=.*/GATEWAY=${GATEWAY}/g" /etc/sysconfig/network-scripts/ifcfg-ens33
    else
        echo "IPADDR=${HOST_IP}" >> /etc/sysconfig/network-scripts/ifcfg-ens33
        echo "GATEWAY=${GATEWAY}" >> /etc/sysconfig/network-scripts/ifcfg-ens33
    fi
    # 找到字符串则执行 && 之后的代码
    # grep IPADDR= /etc/sysconfig/network-scripts/ifcfg-ens33 && sed -i 's/^IPADDR=/IPADDR=192.168.72.120/g' /etc/sysconfig/network-scripts/ifcfg-ens33

    # 使用静态IP,不使用dhcp
    sed -i 's/^BOOTPROTO=/#&/g' /etc/sysconfig/network-scripts/ifcfg-ens33
    
    # 重启网络生效 systemctl restart network
}

# 设置nameserver
function setNameserver(){
#    if [ `grep -c "nameserver 8.8.8.8"  /etc/resolv.conf` -lt 1 ]
#    then
#       echo nameserver 8.8.8.8 >> /etc/resolv.conf
#    fi
    echo nameserver 8.8.8.8 > /etc/resolv.conf
}

function aliyumRepoInstall(){
    # 安装阿里云镜像,和常用软件
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
#    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    # 更新系统yum软件
    yum update -y && yum makecache

    # 第三方库，很多安装包
    yum install epel-release -y

    # ifconfig需要安装ifconfig
    yum install net-tools -y ; yum install vim -y
    yum install maven -y ; yum install java-1.8.0-openjdk
}

# 启动网卡, 启动后重复执行不影响已经启动的网卡 ifup ens33 或者 ifup ifcfg-ens33 都是启动ens33网卡
# 重复执行 提示 RTNETLINK answers: File exists
#ifup ens33

# 初始系统时只需要执行如下方法
sed -i 's/^ONBOOT=no/ONBOOT=yes/g' /etc/sysconfig/network-scripts/ifcfg-ens33 # 将网卡ens33设置为开机启动
setHostIPV4
setNameserver # 设置nameserver
ifup ens33 